<template>
    <div class="container">
        <el-page-header @back="goBack" content="员工部门"></el-page-header>

        <div class="e-m-t-45">
            <el-row type="flex" justify="space-between">
                <el-col :span="3">
                    <el-button type="primary" plain icon="el-icon-plus" @click="creadLargeType">新建{{ categoryTypeObj.name?categoryTypeObj.name+'下级':'' }}</el-button>
                </el-col>
                <!-- <el-col class="e-m-l-15">
                    <el-button icon="el-icon-arrow-left" @click="getList(categoryTypeObj.pid,categoryTypeObj)" v-if="categoryTypeObj.pid > 0">返回上一级</el-button>
                </el-col> -->
                <el-col class="text-right">
                    <el-form :inline="true"  class="nav-bar-form">
                        <el-form-item>
                            <el-checkbox v-model="isUseable">包含未启用</el-checkbox>
                        </el-form-item>
                        <el-form-item>
                            <el-input placeholder="关键词搜索" v-model="key" clearable prefix-icon="el-icon-search" @clear="getList(pid)"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="getList(pid,categoryTypeObj,true)">查询</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
        </div>
        <div class="breadcrumb-box flex">
            <span style="font-size: 14px;line-height: 1;" class="tips">部门导航：</span>
            <el-breadcrumb separator-class="el-icon-arrow-right" class="e-m-b-10">
                <el-breadcrumb-item 
                    v-for="(item, index) in breadcrumbList" 
                    :key="index"
                    @click.native="handleBreadcrumbClick(item, index)"
                    :class="{ 'is-last': index === breadcrumbList.length - 1 }"
                >
                    {{ item.name }}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <el-table :data="list" stripe :border="true">
            <el-table-column label="部门名称" prop="name">
                <template slot-scope="scope">
                    <div class="flex align-items-center">
                        <span class="e-m-l-10">{{ scope.row.name }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="排序" prop="sort"></el-table-column>
            <!-- <el-table-column label="是否启用">
                <template slot-scope="scope">
                    <el-switch v-model="scope.row.state" @change="switchState($event, scope.row.id)"></el-switch>
                </template>
            </el-table-column> -->
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button @click="getList(scope.row.id,scope.row)" type="text" size="small">查看下级</el-button>
                    <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
                    <el-button @click="del(scope.row.id)" type="text" size="small">删除</el-button>
                    <el-button type="text" size="small" @click="toMove(scope.row)">移动</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 新建或编辑部门 -->
        <el-dialog :title="dialogType == 'add' ? '新建部门' : '编辑部门'" :visible.sync="dialogVisible" width="1200px" @close="cancel">
            <el-form ref="form" :model="createdType" :rules="rules" label-width="180px">
                <div class="form-head">部门设置</div>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="createdType.name"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input type="number" v-model="createdType.sort"></el-input>
                </el-form-item>
                <el-form-item label="说明" prop="brief">
                    <el-input
                        type="textarea"
                        :rows="3"
                        placeholder="请输入内容"
                        v-model="createdType.brief">
                    </el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="submitType">{{ dialogType == 'add' ? '添加' : '修改'}}</el-button>
            </span>
        </el-dialog>
        <!-- 移动至 -->
        <el-dialog title="移动至" :visible.sync="moveToDialogVisible" width="30%">
            <el-form ref="ruleForm" v-if="moveToDialogVisible">
                <!-- <el-input v-model="moveToValue" placeholder="请输入可回收物"></el-input> -->
                <el-form-item label="移动到部门" label-width="90px">
                    <el-cascader class="custom-placeholder" ref="chooseType" placeholder="请选择部门" separator="-" @change="SelectType" filterable clearable :props="{
                            lazy: true,
                            checkStrictly: true,
                            lazyLoad: loadType,
                            label: 'name',
                            value: 'id',
                            emitPath: false
                        }" style="width: 100%;margin-right: 20px" v-model="moveTo.toId">
                    </el-cascader>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="moveToDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleToMove">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
// import {
// 	mapState
// } from 'vuex';

export default {
    layout: 'admin',
    head() {
        return {
            title: '员工部门' 
        }
    },
    data() {
        return {
            loading: false,
            pageIndex: 1,
            pageSize: 999,
            total: 0,
            key: '',
            isUseable: false,
            breadcrumbList: [
                {
                    name: '一级部门',
                    pid: 0
                }
            ], // 面包屑导航数组
            state: 1,
            list: [],
            chooseIndex: 0,
            tableData: [],
            pid: 0, //下级部门id
            // 新建或编辑部门
            dialogVisible: false,
            dialogType: 'add',
            categoryTypeObj: {
                icon: ""
            },
            createdType: {
                name: "",
                icon: "",
                brief: "",
                sort: null
            },
            rules: {
                name: [{
                    required: true,
                    message: '请填写废品部门名称',
                    trigger: 'blur'
                }],
                // icon: [{
                //     required: true,
                //     message: '请填写图标名称',
                //     trigger: 'blur'
                // }],
            },
            // 移动至
            moveToDialogVisible: false,
            moveTo:{
                id: 0,
                toId: 0
            }
        }
    },
    // computed: {
    //     ...mapState({
	// 		operatorid: state => state.operatorid,
	// 	})
    // },
    watch:{
        isUseable(val){
            this.getList(this.pid)
        }
    },
    mounted() {
        console.log('默认价格')
        this.getList(0)
    },
    methods: {
        // 返回上一页
        goBack() {
            this.$router.go(-1)
        },
        //加载可回收物
        loadType(node, resolve) {
            console.log('加载可回收物',node)
            const {
                level
            } = node;
            const pid = level === 0 ? 0 : node.value

            this.$axios.get(`Waste/Type/List?pid=${pid}`).then((datas) => {
                const nodes = datas
                    .filter(item => item.usestate === '已启用')
                    .map(c => ({
                        id: c.id,
                        name: c.name,
                        // leaf: c.hasChildren === false // 根据实际接口返回字段判断
                    }))
                resolve(nodes)
            }).catch(() => {
                resolve([]) // 清空加载状态
                this.$message.error('加载失败')
            })
        },
        // 选择分类
        SelectType(v){
            console.log('选择可回收物',v)
            this.toId = v
        },
        // 移动部门
        toMove(row){
            this.moveTo.id = row.id
            this.moveTo.toId = 0
            this.moveToDialogVisible = true
        },
        // 提交移动部门
        handleToMove(){
            this.$axios.post('/Operator/Department/Move',{
                "id": this.moveTo.id,
                "toId": this.moveTo.toId
            }).then(()=>{
                this.moveToDialogVisible = false
                this.$message.success('移动成功')
                this.getList(this.pid,this.categoryTypeObj,true)
            })
        },
        // 点击面包屑项
        handleBreadcrumbClick(item, index) {
            // 点击的不是最后一项时才允许跳转
            if(index < this.breadcrumbList.length - 1) {
                // 如果是根节点
                if(index === 0) {
                    this.getList(0)
                    this.breadcrumbList = this.breadcrumbList.slice(0, 1)
                } else {

                    // 这里需要根据你的接口实现获取父级数据
                    this.getList(item.id,item) 
                    this.breadcrumbList = this.breadcrumbList.slice(0, index + 1)
                }
            }
        },
        // 获取部门
        getList(pid, categoryTypeObj, isSearch = false) {
            console.log('获取部门', pid, categoryTypeObj)
            this.list = []
            // if (pid) {
                this.pid = pid
            // }
            if(categoryTypeObj){
                this.categoryTypeObj = categoryTypeObj
            }else{
                this.categoryTypeObj = {}
            }
            // 当进入下级时更新面包屑
            if(pid > 0 && isSearch == false && categoryTypeObj) {
                this.breadcrumbList.push({
                    ...categoryTypeObj
                })
                // if(this.breadcrumbList.filter((item)=>item.id == categoryTypeObj.id).length == 0){
                //     if(categoryTypeObj.pid == this.breadcrumbList[this.breadcrumbList.length - 1].pid){
                //         this.breadcrumbList.splice(this.breadcrumbList.length - 1, 1)
                //     }
                //     this.breadcrumbList.push({
                //         ...categoryTypeObj
                //     })
                // }
            }
            return this.$axios.post(`/Operator/Department/list`,{
                pageIndex: 1,
                pageSize: 10,
                pid: this.pid,
                Key: this.key
            }).then((res) => {
                this.loading = false
                let datas = res.rows
                this.list = datas;
                
            }).catch(() => {
                this.loading = false
            })
        },
        //修改状态
        switchState(event, id) {
            this.$axios.post(`/Operator/Department/SetState`, {
                ids: [id],
                state: event ? 2 : 1
            }).then((res) => {
                if (res.status == 0) {
                    this.$message.success(res.msg);
                } else {
                    this.$message.error(res.msg);
                }
            }).catch((err) => {
                this.getList(this.pid)
            })
        },
        // 创建部门
        creadLargeType() {
            this.dialogType = 'add'
            this.dialogVisible = true
            this.createdType = {
                name: "",
                brief: "",
                icon: "",
                pid: this.pid
            }
        },
        // 取消创建或编辑部门
        cancel() {
            this.dialogVisible = false
        },
        // 提交创建或修改部门
        submitType() {
            let api = ''
            if (this.dialogType == 'add') {
                api = '/Operator/Department/Create'
            }
            if (this.dialogType == 'edit') {
                api = '/Operator/Department/Edit'
            }

            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.$axios.post(api, this.createdType).then((res) => {
                        this.$message.success(res.msg);
                        this.dialogVisible = false;
                        this.getList(this.pid)
                    }).catch(() => {
                        
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 上传图标
        handleFilesSuccess(res, file) {
            console.log(res,file)
            if (file.status === "success") {
                this.loading = false
                this.createdType.icon = res.path
            }
        },
        edit(obj){
            console.log('edit:',obj)
            this.dialogType = 'edit'
            this.dialogVisible = true
            this.createdType = obj
        },
        // 删除部门
        del(id) {
            return new Promise((resolve, reject) => {
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.get('/Operator/Department/Delete?id=' + id).then((res) => {
                    	this.$message.success(res.msg);
                    	this.getList(this.categoryTypeObj,this.pid)
                    	resolve()
                    })
                })
            })
        },
        removeEmpty(obj) {
            const clean = (value) => {
                if (value === null || value === undefined) return undefined;
                if (typeof value === 'string' && value.trim() === '') return undefined;
                if (Array.isArray(value)) {
                    return value.map(clean).filter(item => item !== undefined);
                }
                if (typeof value === 'object') {
                    const result = {};
                    Object.keys(value).forEach(key => {
                        const cleaned = clean(value[key]);
                        if (cleaned !== undefined) result[key] = cleaned;
                    });
                    return Object.keys(result).length ? result : undefined;
                }
                return value;
            };
            return clean(obj) || {};
        }
    }
}
</script>

<style lang="scss" scoped>
    ::v-deep{
        .el-breadcrumb {
            margin-bottom: 20px;
            .el-breadcrumb__item {
                cursor: pointer;
                &:hover {
                    color: var(--main);
                }
                &.is-last {
                    cursor: default;
                    color: #999;
                    &:hover {
                        color: #999;
                    }
                }
            }
        }
    }
    .form-head {
        background-color: var(--light);
        padding: 8px 12px;
        font-size: 14px;
        border-radius: 3px;
        color: var(--dark);
        margin-bottom: 10px;
    }
    //默认部门列表
    .type-list {
        margin-top: 15px;
        display: flex;
        min-height: calc(100vh - 275px);

        .left-box {
            .item {
                // display: inline-block;
                width: 150px;
                height: 50px;
                // line-height: 40px;
                text-align: center;
                // border: 1px solid #e6e6e6;
                // margin-right: 10px;
                margin-bottom: 10px;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: pointer;

                &:last-child {
                    margin-bottom: 0;
                }

                &:hover {
                    background: #f7f8fa;
                }

                &.on {
                    background-color: #02d5d61f;

                    span {
                        color: var(--main);
                        border-left: 3px solid var(--main);
                        display: block;
                        line-height: 1.4em;
                        width: 100%;
                    }
                }
            }
        }

        .right-box {
            // flex: 1;
            background: #f7f8fa;
            padding: 15px;
            // width: calc(100vw - 490px);

            .cell {
                background-color: #fff;
                padding: 30px;
                border-radius: 5px;
                min-height: 100%;
                box-sizing: border-box;
                box-shadow: 0 0 16px 0 rgb(0 0 0 / 4%);

                .title-item {
                    // background: #f7f8fa;
                    // color: var(--grey);
                    // padding: 10px;
                }
            }
        }
    }
</style>
